package org.carota.itext5;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.carota.pdf.PdfConfigurer;
import org.carota.pdf.PdfProcessor;

import java.io.IOException;

/**
 * @author : AnWen
 * @version :1.0
 * @email : anwen375@qq.com
 * @since : 2023-03-29 18:53
 */
@Slf4j
@NoArgsConstructor
public class AntiFakeConfigurer extends PdfConfigurer {

    private Image image;


    public AntiFakeConfigurer(PdfProcessor processor) {
       super(processor);
    }

    public AntiFakeConfigurer image(java.awt.Image image) {
        try {
            this.image = Image.getInstance (image, null);
        } catch (BadElementException | IOException e) {
            log.error ("初始化防伪标记异常: ",e);
            throw new RuntimeException ("初始化防伪标记异常");
        }
        return this;
    }


    @Override
    protected void checkParams() {
        checkParams("防伪",image, "image");
    }

    /**
     * 防伪二维码
     */
    @Override
    public void execute() {
        PdfStamper stamper = processor.getStamper ();
        PdfReader reader = stamper.getReader ();
        try {
            for (int i = 1; i <= reader.getNumberOfPages (); i++) {
                PdfContentByte overContent = stamper.getOverContent (i);
                float y = overContent.getPdfDocument ().getPageSize ().getHeight () - image.getHeight ();
                image.setAbsolutePosition (0, y);
                overContent.addImage (image);
            }
        } catch (DocumentException e) {
            log.error ("添加防伪水印失败: ", e);
            throw new RuntimeException ("添加防伪水印失败");
        }
    }



    @Override
    public int getOrder() {
        return 10;
    }
}
